<!-- BOM管理 -->
<template>
  <div class="bom-management">
    <div class="title-section">
      <h2>BOM管理</h2>
      <button class="btn-primary" @click="openDialog()">新建</button>
    </div>

    <!-- 筛选区域 -->
    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <label>BOM编号</label>
          <input type="text" v-model="searchForm.bomCode" placeholder="请输入BOM编号">
        </div>
        <div class="filter-item">
          <label>BOM名称</label>
          <input type="text" v-model="searchForm.bomName" placeholder="请输入BOM名称">
        </div>
        <div class="filter-item">
          <label>产品编码</label>
          <input type="text" v-model="searchForm.productCode" placeholder="请输入产品编码">
        </div>
        <div class="filter-item">
          <label>产品名称</label>
          <input type="text" v-model="searchForm.productName" placeholder="请输入产品名称">
        </div>
        <div class="filter-item">
          <label>状态</label>
          <select v-model="searchForm.status">
            <option value="">全部</option>
            <option value="1">启用</option>
            <option value="0">停用</option>
          </select>
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="search">搜索</button>
        <button class="btn-secondary" @click="resetSearch">重置</button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
        <tr>
          <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll"></th>
          <th>BOM编号</th>
          <th>BOM名称</th>
          <th>产品名称</th>
          <th>产品编码</th>
          <th>规格</th>
          <th>分类</th>
          <th>单位</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(row, index) in tableData" :key="index">
          <td><input type="checkbox" v-model="row.selected" @change="updateSelectAll"></td>
          <td class="link-style" @click="openDialog(row)">
            {{ row.bomCode }}
          </td>
          <td>{{ row.bomName }}</td>
          <td>{{ row.productName }}</td>
          <td>{{ row.productCode }}</td>
          <td>{{ row.specification }}</td>
          <td>{{ categoryText(row.category) }}</td>
          <td>{{ row.unitName }}</td>
          <td>
              <span :class="['status-badge', row.status === 1 ? 'status-active' : 'status-inactive']">
                {{ row.status === 1 ? '启用' : '停用' }}
              </span>
          </td>
          <td>
            <button class="btn-link" @click="openDialog(row)">编辑</button>
            <button class="btn-link btn-danger" @click="deleteItem(row.bomId)">删除</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
        <label>全选</label>
        <button class="btn-secondary" @click="exportData">导出</button>
        <button class="btn-danger" @click="batchDelete" v-if="selectedItems.length > 0">
          批量删除({{ selectedItems.length }})
        </button>
      </div>
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage <= 1">&lt;</button>
        <button v-for="page in displayPages" :key="page"
                :class="{ active: currentPage === page }"
                @click="goToPage(page)">{{ page }}</button>
        <button @click="nextPage" :disabled="currentPage >= totalPages">&gt;</button>
        <select v-model="pageSize" @change="handlePageSizeChange">
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
        <span class="page-info">共 {{ total }} 条记录</span>
      </div>
    </div>

    <!-- BOM表单对话框 -->
    <div v-if="showDialog" class="dialog-overlay" @click="closeDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>{{ isEdit ? '编辑BOM' : '新建BOM' }}</h3>
          <button class="btn-close" @click="closeDialog">&times;</button>
        </div>
        <div class="dialog-body">
          <form @submit.prevent="submitForm">
            <div class="form-row">
              <div class="form-group">
                <label>BOM名称 <span class="required">*</span></label>
                <input type="text" v-model="form.bomName" required placeholder="请输入BOM名称">
              </div>
              <div class="form-group">
                <label>产品名称 <span class="required">*</span></label>
                <input type="text" v-model="form.productName" required placeholder="请输入产品名称">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>产品编码 <span class="required">*</span></label>
                <input type="text" v-model="form.productCode" required placeholder="请输入产品编码">
              </div>
              <div class="form-group">
                <label>规格</label>
                <input type="text" v-model="form.specification" placeholder="请输入规格">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>分类</label>
                <select v-model="form.category">
                  <option :value="0">成品</option>
                  <option :value="1">半成品</option>
                  <option :value="2">残次品</option>
                </select>
              </div>
              <div class="form-group">
                <label>单位名称</label>
                <input type="text" v-model="form.unitName" placeholder="请输入单位名称">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>状态</label>
                <select v-model="form.status">
                  <option value="1">启用</option>
                  <option value="0">停用</option>
                </select>
              </div>
            </div>
            <div class="form-actions">
              <button type="submit" class="btn-primary" :disabled="loading">
                {{ loading ? '保存中...' : '保存' }}
              </button>
              <button type="button" class="btn-secondary" @click="closeDialog">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { bomApi } from '@/api/bom.js'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'BOMManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        bomCode: '',
        bomName: '',
        productCode: '',
        productName: '',
        status: ''
      },
      // 表格数据
      tableData: [],
      selectAll: false,
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      totalPages: 0,
      // 对话框
      showDialog: false,
      isEdit: false,
      loading: false,
      // 表单数据
      form: {
        bomId: null,
        bomName: '',
        productName: '',
        productCode: '',
        specification: '',
        category: '',
        unitName: '',
        status: 1
      }
    }
  },
  computed: {
    selectedItems() {
      return this.tableData.filter(item => item.selected)
    },
    displayPages() {
      const pages = []
      const start = Math.max(1, this.currentPage - 2)
      const end = Math.min(this.totalPages, this.currentPage + 2)

      for (let i = start; i <= end; i++) {
        pages.push(i)
      }
      return pages
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 数字分类转中文
    categoryText(val) {
      if (val === 0 || val === '0') return '成品'
      if (val === 1 || val === '1') return '半成品'
      if (val === 2 || val === '2') return '残次品'
      return ''
    },
    // 加载数据
    async loadData() {
      try {
        const params = {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        }

        const response = await bomApi.page(params)
        const result = response.data.data

        this.tableData = result.records.map(item => ({
          ...item,
          selected: false
        }))
        this.total = result.total
        this.totalPages = Math.ceil(result.total / this.pageSize)
        this.updateSelectAll()
      } catch (error) {
        console.error('加载数据失败:', error)
      }
    },

    // 搜索
    search() {
      this.currentPage = 1
      this.loadData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        bomCode: '',
        bomName: '',
        productCode: '',
        productName: '',
        status: ''
      }
      this.search()
    },

    // 分页操作
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.loadData()
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.loadData()
      }
    },
    goToPage(page) {
      this.currentPage = page
      this.loadData()
    },
    handlePageSizeChange() {
      this.currentPage = 1
      this.loadData()
    },

    // 全选操作
    toggleSelectAll() {
      this.tableData.forEach(item => {
        item.selected = this.selectAll
      })
    },
    updateSelectAll() {
      this.selectAll = this.tableData.length > 0 && this.tableData.every(item => item.selected)
    },

    // 打开对话框
    openDialog(item = null) {
      this.isEdit = !!item
      if (item) {
        this.form = { ...item }
      } else {
        this.form = {
          bomId: null,
          bomName: '',
          productName: '',
          productCode: '',
          specification: '',
          category: '',
          unitName: '',
          status: 1
        }
      }
      this.showDialog = true
    },

    // 关闭对话框
    closeDialog() {
      this.showDialog = false
      this.form = {
        bomId: null,
        bomName: '',
        productName: '',
        productCode: '',
        specification: '',
        category: '',
        unitName: '',
        status: 1
      }
    },

    // 提交表单
    async submitForm() {
      try {
        this.loading = true

        if (this.isEdit) {
          await bomApi.update(this.form)
        } else {
          await bomApi.add(this.form)
        }

        this.closeDialog()
        this.loadData()
        ElMessage.success(this.isEdit ? '更新成功' : '新增成功')
      } catch (error) {
        console.error('保存失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 删除单个项目
    async deleteItem(bomId) {
      try {
        await ElMessageBox.confirm('确定要删除这条BOM记录吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch {
        return
      }

      try {
        await bomApi.delete(bomId)
        this.loadData()
        ElMessage.success('删除成功')
      } catch (error) {
        console.error('删除失败:', error)
      }
    },

    // 批量删除
    async batchDelete() {
      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${this.selectedItems.length} 条记录吗？`, '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch {
        return
      }

      try {
        const promises = this.selectedItems.map(item => bomApi.delete(item.bomId))
        await Promise.all(promises)
        this.loadData()
        ElMessage.success('批量删除成功')
      } catch (error) {
        console.error('批量删除失败:', error)
      }
    },

    // 导出数据
    async exportData() {
      try {
        const response = await bomApi.export(this.searchForm)

        // 创建下载链接
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = 'BOM信息.xlsx'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.bom-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.title-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section h2 {
  font-size: 20px;
  font-weight: bold;
}

.controls-section {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.filters {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  white-space: nowrap;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 150px;
}

.actions {
  display: flex;
  gap: 10px;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary:hover {
  background-color: #66b1ff;
}

.btn-primary:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.btn-danger {
  background-color: #f56c6c;
  color: white;
  border: 1px solid #f56c6c;
}

.btn-danger:hover {
  background-color: #f78989;
}

.btn-link {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  padding: 4px 8px;
  margin: 0 4px;
}

.btn-link:hover {
  text-decoration: underline;
}

.btn-link.btn-danger {
  color: #f56c6c;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.link-style {
  color: #409eff;
  cursor: pointer;
}

.link-style:hover {
  text-decoration: underline;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-active {
  background-color: #f0f9ff;
  color: #67c23a;
}

.status-inactive {
  background-color: #fef0f0;
  color: #f56c6c;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:hover:not(:disabled) {
  color: #409eff;
  border-color: #c6e2ff;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination button:disabled {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.page-info {
  margin-left: 8px;
  color: #606266;
  font-size: 14px;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: #fff;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #909399;
}

.btn-close:hover {
  color: #606266;
}

.dialog-body {
  padding: 20px;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.required {
  color: #f56c6c;
}

.form-group input,
.form-group select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #409eff;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}
</style>


